/**
 * 属性型指令，设置所在元素的背景色。
 */
import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core';

@Directive({
  selector: '[myHighlight]'
})
export class HightlightDirective {
  private _defaultColor = 'red';

  constructor(
    private highlightColor: string,
    private el: ElementRef,
    private renderer: Renderer) {
    console.log(`* Contact myHighlight called for ${el.nativeElement.tagName}`);
  }

  @Input() set defaultcolor(colorName: string) {
    this._defaultColor = colorName || this._defaultColor;
  }

  @HostListener('mouseenter')
  public onMouseEnter() {
    this.highlight(this.highlightColor || this._defaultColor);
  }
  @HostListener('mouseleave')
  public onMouseLeave() {
    this.highlight(null);
  }

  public highlight(color: string) {
    this.renderer.setElementStyle(this.el.nativeElement, 'backgroundColor', color);
  }
}
